'''
    Pegaso
    Copyright (c) 2012 Dario Tognacci

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''

from collections import OrderedDict

# This dictionary contains all the 'typedef' and 'define' statements found in
# the C header.
statements_table = OrderedDict()
# Scroll to the end of the file to find where the C types are added to the table.

# This dictionary contains references only to the function statements present in
# statements_table. 
function_table = OrderedDict()

# This class represents a generic statement in the C header file.
class Statement(object):
    def __getitem__(self, key): return self.data[key]
    def __setitem__(self, key, item): self.data[key] = item
    def get_xml_representation(self): return "<generic_statement />"
    
    def __repr__(self):
        elements = []
        for key in self.data:
            if self.data[key] is not None:
                elements.append("{0}={1}".format(key,self.data[key]))
            else:
                elements.append("{0}=None".format(key))
        return self.__class__.__name__ + "(" + ",".join(elements) + ")"
    
    def get_xdr_representation(self): return ""

# This class represents all C declarations that are not a structure. So, for
# example, an int declaration, a pointer to double declaration, an array of char
# declaration, and so on.
class SimpleType(Statement):
    
    def __init__(self):
        self.name = "SimpleType"
        self.data = {
            'identifier' : "",
            'type' : "",
            'qualifiers' : [],
            'array' : False,
            'array_dimension' : "",
            'pointer' : False,
            'size_of' : None,
            'trasform_ptr' : None,
            'inside_struct' : False,
            'dont_print': False
        }
    
    def get_xml_representation(self):
        qualifiers_repr = ""
        if self.data['qualifiers'] == []:
            qualifiers_repr = "None"
        else:
            qualifiers_repr = self.data['qualifiers'][0]
            for elem in self.data['qualifiers'][1:]:
                qualifiers_repr = qualifiers_repr + " " + elem
        
        xml = ['<simple_type>']
        xml.append('<identifier>{0}</identifier>'.format(self.data['identifier']))
        xml.append('<type>{0}</type>'.format(self.data['type']))
        xml.append('<qualifiers>{0}</qualifiers>'.format(qualifiers_repr))
        xml.append('<array>{0}</array>'.format(self.data['array']))
        
        if self.data['array_dimension'] is not "":
            xml.append('<array_dimension>{0}</array_dimension>'.format(
                       self.data['array_dimension']))
        else:
            xml.append('<array_dimension>None</array_dimension>')
        
        xml.append('<pointer>{0}</pointer>'.format(self.data['pointer']))
        
        if self.data['size_of']:
            xml.append(self.data['size_of'].get_xml_representation())
        if self.data['trasform_ptr'] is not None:
            xml.append(self.data['trasform_ptr'].get_xml_representation())

        xml.append('</simple_type>')
        return "".join(xml)
    
    def get_xdr_remote_representation(self):
        if self['dont_print'] is True:
            return ""
        
        type_repr = ["typedef"]
        if self['qualifiers'] is not []:
            type_repr.append(" ".join(self['qualifiers']))
        if (self['type'] not in ["char","double","float","int","void", "long", "short"]):
            type_repr.append("REMOTE_" + self['type'])
        else:
            type_repr.append(self['type'])
        if self['pointer']:
            type_repr.append("*")
        type_repr.append("REMOTE_" + self['identifier'])
        if self['array']:
            type_repr.append("[]")
        repr = []
        repr.append(" ".join(type_repr) + ";")
        return "\n".join(repr)
    
    def get_remote_statement(self):
        
        type_repr = []
        if self['trasform_ptr'] is not None:
            new_type = self['trasform_ptr'].type
            type_repr.append("{0} {1}<>".format("REMOTE_" + new_type, self['identifier']))
        else:
            if self['qualifiers'] != []:
                type_repr.append(" ".join(self['qualifiers']))
            type_repr.append("REMOTE_" + self['type'])
            if self['pointer']:
                type_repr.append("*")
            if self['array']:
                if self['array_dimension'] is not "":
                    type_repr.append("{0}[{1}]".format(self['identifier'],
                                                       self['array_dimension']))
                else:
                    type_repr.append("{0}[]".format(self['identifier']))
            else:
                type_repr.append("{0}".format(self['identifier']))
        return " ".join(type_repr)
    
    def get_xdr_local_representation(self):
        if self['dont_print'] is True:
            return ""
        
        type_repr = ["typedef"]
        if self['qualifiers'] is not []:
            type_repr.append(" ".join(self['qualifiers']))
        type_repr.append(self['type'])
        if self['pointer']:
            type_repr.append("*")
        type_repr.append(self['identifier'])
        if self['array']:
            type_repr.append("[]")
        repr = []
        repr.append(" ".join(type_repr) + ";")
        return "\n".join(repr)
    
    def get_local_statement(self):
        type_repr = []
        if self['qualifiers'] != []:
            type_repr.append(" ".join(self['qualifiers']))
        type_repr.append(self['type'])
        if self['pointer']:
            type_repr.append("*")
        if self['array']:
            if self['array_dimension'] is not "":
                type_repr.append("{0}[{1}]".format(self['identifier'],
                                                   self['array_dimension']))
            else:
                type_repr.append("{0}[]".format(self['identifier']))
        else:
            type_repr.append("{0}".format(self['identifier']))
        return " ".join(type_repr)


# This class represents a C struct declaration.
class StructType(Statement):
    
    def __init__(self):
        self.data = {
            'identifier' : "",
            'struct_identifier' : "",
            'fields' : [],
            'nested' : False
        }
    
    def get_xml_representation(self):
        xml = ["<struct_type>"]
        if self.data['identifier'] is not "":
            xml.append("<identifier>{0}</identifier>".format(self.data['identifier']))
        xml.append("<struct_identifier>{0}</struct_identifier>".format(
                   self.data['struct_identifier']))
        xml.append("<fields>")
        for field in self.data['fields']:
            xml.append("<field>")
            xml.append(field.get_xml_representation())
            xml.append("</field>")
        xml.append("</fields>")
        xml.append("</struct_type>")
        return "".join(xml)
    
    def get_xdr_remote_representation(self,):
        repr = []
        repr.append("struct {0} {{".format("REMOTE_" + self['struct_identifier']))
        for field in self['fields']:
                repr.append("\t" + field.get_remote_statement() + ";")
        repr.append("};")
        repr.append("typedef struct {0} {1};".format(("REMOTE_" + self['struct_identifier']),
                                                     ("REMOTE_" + self['identifier'])))
        return "\n".join(repr)
    
    def get_xdr_local_representation(self):
        repr = []
        repr.append("struct {0} {{".format(self['struct_identifier']))
        for field in self['fields']:
                repr.append("\t" + field.get_local_statement() + ";")
        repr.append("};")
        repr.append("typedef struct {0} {1};".format(self['struct_identifier'],
                                                     self['identifier']))
        return "\n".join(repr)
    
    def get_local_statement(self):
        repr = []
        repr.append("struct {0} {".format(self['struct_identifier']))
        for field in self['fields']:
                repr.append(field.get_string_representation() + ";")
        repr.append("};")
    
    def get_remote_statement(self):
        repr = []
        repr.append("struct {0} {".format(self['struct_identifier']))
        for field in self['fields']:
                repr.append(field.get_string_representation() + ";")
        repr.append("};")
        


# This class represents a SizeOf directive found in a comment on the side of
# SympleType declaration. A link to an instance of this class could be found
# in the SympleType size_of field. 
class SizeOfDirective(object):
    
    def __init__(self, variable, pointer=False):
        self.variable = variable
        self.pointer = pointer
    
    @property
    def get_variable(self):
        return self.variable
    
    def set_variable(self, variable):
        self.variable = variable

    @property
    def get_pointer(self):
        return self.pointer
    
    def __repr__(self):
        return "SizeOf({0},{1})".format(self.variable, self.pointer)
    
    def get_xml_representation(self):
        xml = ["<size_of_directive>"]
        xml.append("<variable>{0}</variable>".format(self.variable))
        xml.append("<pointer>{0}</pointer>".format(self.pointer))
        xml.append("</size_of_directive>")
        return "".join(xml)


# This class represents a TrasformPtr directive.
class TrasformPtrDirective(object):
    
    def __init__(self, type, dimension):
        self.type = type
        self.dimension = dimension
    
    @property
    def get_type(self):
        return self.type
    
    @property
    def get_dimension(self):
        return self.dimension
    
    def __repr__(self):
        return "TrasformPtr({0},{1})".format(self.type, self.dimension)
    
    def get_xml_representation(self):
        xml = ["<trasform_ptr_directive>"]
        xml.append("<type>{0}</type>".format(self.type))
        xml.append("<dimension>{0}</dimension>".format(self.dimension))
        xml.append("</trasform_ptr_directive>")
        return "".join(xml)


# This class represents a parameter passed through a function.
class ParameterType():
    
    def __init__(self, type, identifier, size_of, trasform_ptr, modifiable):
        self.identifier = identifier
        self.type = type
        self.size_of = size_of
        self.trasform_ptr = trasform_ptr
        self.modifiable = modifiable
    
    def __getitem__(self,key):
        if key == 'identifier':
            return self.identifier
        elif key == 'type':
            return self.type
        elif key == 'size_of':
            return self.size_of
        elif key == 'trasform_ptr':
            return self.trasform_ptr
        elif key == 'modifiable':
            return self.modifiable
    
    @property
    def get_identifier(self):
        return self.identifier
    
    @property
    def get_type(self):
        return self.type
    
    @property
    def get_size_of(self):
        return self.size_of
    
    @property
    def set_size_of(self, size_of):
        self.size_of = size_of
    
    @property
    def get_trasform_ptr(self):
        return self.trasform_ptr
    
    @property
    def get_modifiable(self):
        return self.modifiable
    
    def get_xml_representation(self):
        xml = ["<parameter>"]
        xml.append("<type>{0}</type>".format(self.type))
        xml.append("<identifier>{0}</identifier>".format(self.identifier))
        if self.trasform_ptr is not None:
            xml.append(self.size_of.get_xml_representation())
        if self.modifiable is True:
            xml.append("<modifiable/>")
        xml.append("</parameter>")
        return "".join(xml)
        
    
    def get_str_representation(self):
        return "{0} {1}".format(self.type, self.identifier)
    
    def __repr__(self):
        if self.size_of and self.trasform_ptr:
            return "{0} {1}<S({2},{3})><T({4},{5})>".format(self.type,
                                                            self.identifier,
                                                          self.size_of.variable,
                                                          self.size_of.dimension,
                                                          self.trasform_ptr.type,
                                                          self.trasform_ptr.dimension)
        elif self.size_of:
            return "{0} {1}<S({2},{3})>".format(self.type, self.identifier,
                                                self.size_of.variable,
                                                self.size_of.dimension)
        elif self.trasform_ptr:
            return "{0} {1}<T({2},{3})>".format(self.type, self.identifier,
                                                self.trasform_ptr.type,
                                                self.trasform_ptr.dimension)
        else:
            return "{0} {1}".format(self.type, self.identifier)


class FunctionType():
    
    def __init__(self):
        self.data = {
            'identifier' : "",
            'return_type' : "",
            'parameters' : []
        }

    def __getitem__(self, key): return self.data[key]
    def __setitem__(self, key, value): self.data[key] = value
    
    def get_xml_representation(self):
        xml = ["<function_type>"]
        xml.append("<identifier>{0}</identifier>".format(self.data['identifier']))
        xml.append("<return_type>{0}</return_type>".format(self.data['return_type']))
        xml.append("<parameters>")
        for parameter in self['parameters']:
            xml.append(parameter.get_xml_representation())
        xml.append("</parameters>")
        xml.append("</function_type>")
        return "".join(xml)

    def get_str_representation(self):
        params = []
        for parameter in self['parameters']:
            params.append(parameter.get_str_representation())
        params = ", ".join(params)
        return "{0} (*{1})({2})".format(self['return_type'], self['identifier'],
                                 params)
    
    def get_xdr_representation(self):
        repr = ["#ifdef RPC_HDR"]
        params = []
        for parameter in self['parameters']:
            params.append(parameter.get_str_representation())
        params = ", ".join(params)
        repr.append("%" + "typedef {0} (*{1})({2});".format(self['return_type'],
                                               self['identifier'], params))
        repr.append("#endif")
        return "\n".join(repr)


### Grammar for the preprocessor directives.

# This class represents the define preprocessor directive.
class DefineDirective(Statement):
    
    def __init__(self):
        self.data = {
            'identifier' : "",
            'parameters' : "",
            'repl_token_list' : ""
        }
    
    def get_xml_representation(self):
        xml = ["<define>"]
        xml.append("<identifier>{0}</identifier>".format(self.data["identifier"]))
        xml.append("<parameters>{0}</parameters>".format(self.data["parameters"]))
        xml.append("<repl_token_list>{0}</repl_token_list>".format( 
                   self.data["repl_token_list"]))
        xml.append("</define>")
        return "".join(xml)
    
    def get_xdr_representation(self):
        repr = ["#ifdef RPC_HDR"]
        if self.data['parameters'] is not "":
            repr.append("%#define " + "{0}({1}) {2}".format(self['identifier'],
                                                self['parameters'],
                                                self['repl_token_list']))
        elif self.data['repl_token_list'] is not "":
            repr.append("%#define " + "{0} {1}".format(self['identifier'],
                                               self['repl_token_list']))
        else:
            repr.append("%#define " + "{0}".format(self['identifier']))
        repr.append("#endif")
        return "\n".join(repr)


# This class represents the if preprocessor directive.
class IfDirective(Statement):
    
    def __init__(self):
        self.data = {
            'test' : ""
        }
    
    def get_xml_representation(self):
        xml = ["<if>"]
        xml.append("<test>{0}</test>".format(self.data['test']))
        xml.append("</if>")
        return "".join(xml)
    
    def get_xdr_representation(self):
        repr = ["#ifdef RPC_HDR"]
        repr.append("%#if " + "{0}".format(self['test']))
        repr.append("#endif")
        return "\n".join(repr)


# This class represents the ifdef preprocessor directive.
class IfDefDirective(Statement):
    
    def __init__(self):
        self.data = {
            'test' : ""
        }
    
    def get_xml_representation(self):
        xml = ["<ifdef>"]
        xml.append("<test>{0}</test>".format(self.data['test']))
        xml.append("</ifdef>")
        return "".join(xml)
    
    def get_xdr_representation(self):
        repr = ["#ifdef RPC_HDR"]
        repr.append("%#ifdef " + "{0}".format(self['test']))
        repr.append("#endif")
        return "\n".join(repr)


# This class represents the ifndef preprocessor directive.
class IfNDefDirective(Statement):
    
    def __init__(self):
        self.data = {
            'test' : ""
        }
    
    def get_xml_representation(self):
        xml = ["<ifndef>"]
        xml.append("<test>{0}</test>".format(self.data['test']))
        xml.append("</ifndef>")
        return "".join(xml)
    
    def get_xdr_representation(self):
        repr = ["#ifdef RPC_HDR"]
        repr.append("%#ifndef " + "{0}".format(self['test']))
        repr.append("#endif")
        return "\n".join(repr)


# This class represents the else preprocessor directive.
class ElseDirective(Statement):
    def __init__(self): self.data = {}
    def get_xml_representation(self): return "<else />"
    
    def get_xdr_representation(self):
        repr = ["#ifdef RPC_HDR"]
        repr.append("%#else")
        repr.append("#endif")
        return "\n".join(repr)


# This class represents the elif preprocessor directive.
class ElifDirective(Statement):
    
    def __init__(self):
        self.data = {
            'test' : ""
        }
    
    def get_xml_representation(self):
        xml = ["<elif>"]
        xml.append("<test>{0}</test>".format(self.data['test']))
        xml.append("</elif>")
        return "".join(xml)
    
    def get_xdr_representation(self):
        repr = ["#ifdef RPC_HDR"]
        repr.append("%#elif " + "{0}".format(self['test']))
        repr.append("#endif")
        return "\n".join(repr)


# This class represents the endif preprocessor directive.
class EndIfDirective(Statement):
    def __init__(self): self.data = {}
    def get_xml_representation(self): return "<endif />"
    
    def get_xdr_representation(self):
        repr = ["#ifdef RPC_HDR"]
        repr.append("%#endif")
        repr.append("#endif")
        return "\n".join(repr)


# This class represents the undef preprocessor directive.
class UnDefDirective(Statement):
    def __init__(self):
        self.data = {
            'identifier' : ""
        }
    
    def get_xml_representation(self):
        xml = ["<undef>"]
        xml.append("<identifier>{0}</identifier>".format(self.data['identifier']))
        xml.append("</undef>")
        return "".join(xml)
    
    def get_xdr_representation(self):
        repr = ["#ifdef RPC_HDR"]
        repr.append("%#undef " + "{0}".format(self['identifier']))
        repr.append("#endif")
        return "\n".join(repr)


# This class represents the include preprocessor directive.
class IncludeDirective(Statement):
    
    def __init__(self):
        self.data = {
            'filename' : ""
        }
    
    def get_xml_representation(self):
        xml = ["<include>"]
        xml.append("<filename>{0}</filename>".format(self.data['filename']))
        xml.append("</include>")
        return "".join(xml)
    
    def get_xdr_representation(self):
        repr = ["#ifdef RPC_HDR"]
        repr.append("%#include " + "{0}".format(self['filename']))
        repr.append("#endif")
        return "\n".join(repr)


# This class represents the extern C keyword.
class ExternKeyword(Statement):
    def __init__(self): self.data = {}
    def get_xml_representation(self): return ("<extern />")
    
    def get_xdr_representation(self):
        repr = ["#ifdef RPC_HDR"]
        repr.append("%extern \"C\"")
        repr.append("#endif")
        return "\n".join(repr)


# This class represents an opening brace.
class OpeningBraceKeyword(Statement):
    def __init__(self): self.data = {}
    def get_xml_representation(self): return ("<opening_brace />")
    
    def get_xdr_representation(self):
        repr = ["#ifdef RPC_HDR"]
        repr.append("%{")
        repr.append("#endif")
        return "\n".join(repr)


# This class represents a closing brace.
class ClosingBraceKeyword(Statement):
    def __init__(self): self.data = {}
    def get_xml_representation(self): return ("<closing_brace />")
    
    def get_xdr_representation(self):
        repr = ["#ifdef RPC_HDR"]
        repr.append("%}")
        repr.append("#endif")
        return "\n".join(repr)

# Adding the char type to statements table.
s_type = SimpleType()
s_type['identifier'] = 'char'
s_type['type'] = 'char'
s_type['dont_print'] = True
statements_table['char'] = s_type

# Adding the double type to statements table.
s_type = SimpleType()
s_type['identifier'] = 'double'
s_type['type'] = 'double'
s_type['dont_print'] = True
statements_table['double'] = s_type

# Adding the float type to statements table.
s_type = SimpleType()
s_type['identifier'] = 'float'
s_type['type'] = 'float'
s_type['dont_print'] = True
statements_table['float'] = s_type

# Adding the int type to statements table.
s_type = SimpleType()
s_type['identifier'] = 'int'
s_type['type'] = 'int'
s_type['dont_print'] = True
statements_table['int'] = s_type

# Adding the void type to statements table.
s_type = SimpleType()
s_type['identifier'] = 'void'
s_type['type'] = 'void'
s_type['dont_print'] = True
statements_table['void'] = s_type

# Adding the long type to statements table.
s_type = SimpleType()
s_type['identifier'] = 'long'
s_type['type'] = 'long'
s_type['dont_print'] = True
statements_table['long'] = s_type

# Adding the short type to statements table.
s_type = SimpleType()
s_type['identifier'] = 'short'
s_type['type'] = 'short'
s_type['dont_print'] = True
statements_table['short'] = s_type
